package com.zxbit.flash.ui.activity.login;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.accountkit.AccountKitLoginResult;
import com.facebook.accountkit.ui.AccountKitActivity;
import com.facebook.accountkit.ui.AccountKitConfiguration;
import com.facebook.accountkit.ui.LoginType;
import com.facebook.accountkit.ui.ThemeUIManager;
import com.zxbit.flash.BuildConfig;
import com.zxbit.flash.R;
import com.zxbit.flash.cache.Acache;
import com.zxbit.flash.cache.AcacheKeys;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.mvpview.LoginMvpView;
import com.zxbit.flash.presenter.LoginPresenter;
import com.zxbit.flash.response.FaceBookLoginResponse;
import com.zxbit.flash.response.LoginResponse;
import com.zxbit.flash.rxbus.EventMsg;
import com.zxbit.flash.rxbus.Events;
import com.zxbit.flash.rxbus.RxBus;
import com.zxbit.flash.utils.NoDoubleClickUtils;
import com.zxbit.flash.utils.StringUtils;
import com.zxbit.flash.utils.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(name = "选择登录方式页面", path = RouterMap.FACEBOOKLOGIN)
public class LoginMethodActivity extends BaseTitleActivity implements LoginMvpView {

    @BindView(R.id.tv_login_by_facebook)
    TextView tvLoginByFacebook;
    @BindView(R.id.display_show_text)
    TextView displayShowText;
    @BindView(R.id.login_by_user_and_psw)
    TextView loginByUserAndPsw;
    private LoginPresenter loginPresenter;
    private String kitCode;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void onUIReady() {
        loginPresenter = new LoginPresenter(this);
        if (BuildConfig.DEBUG) {
            displayShowText.setVisibility(View.VISIBLE);
            loginByUserAndPsw.setVisibility(View.VISIBLE);
        } else {
            displayShowText.setVisibility(View.GONE);
            loginByUserAndPsw.setVisibility(View.GONE);
        }
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_login_method;
    }

    @OnClick({R.id.tv_login_by_facebook, R.id.login_by_user_and_psw, R.id.display_show_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login_by_facebook:
//                if (StringUtils.isEmpty(kitCode)) {
                    faceBookLogin();
//                } else {
//                    accountKitLogin(kitCode);
//                }
                break;
            case R.id.login_by_user_and_psw:
                ARouter.getInstance().build(RouterMap.LOGIN_PAGE).navigation();
                finish();
                break;
            case R.id.display_show_text:
                accountKitLogin(displayShowText.getText().toString());
                break;
        }
    }

    private void faceBookLogin() {
        final Intent intent = new Intent(this, AccountKitActivity.class);
        AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder = new
                AccountKitConfiguration.AccountKitConfigurationBuilder(LoginType.PHONE,
                AccountKitActivity.ResponseType.CODE); // or .ResponseType.TOKEN

        configurationBuilder.setUIManager(new ThemeUIManager(R.style.AppLoginTheme));

        intent.putExtra(AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
                configurationBuilder.build());
        startActivityForResult(intent, Constant.REQUEST_CODE_FACEBOOK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_CODE_FACEBOOK) { // confirm that this response
            // matches your request
            AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult
                    .RESULT_KEY);
            String toastMessage;
            if (loginResult.getError() != null) {
                toastMessage = loginResult.getError().getErrorType().getMessage();
            } else if (loginResult.wasCancelled()) {
                toastMessage = "Login Cancelled";
            } else {
                toastMessage = "Success";
                kitCode = loginResult.getAuthorizationCode();
                if (BuildConfig.DEBUG) {
                    displayShowText.setText(kitCode);
                }
//                accountKitLogin(kitCode);
                accountKitLogin(loginResult.getAuthorizationCode());
            }
            ToastUtils.showShort(this, toastMessage);

        }
    }

    private void accountKitLogin(String code) {
        if (NoDoubleClickUtils.isDoubleClick()) return;
        loginPresenter.facebookLogin(code);
        showLoadingView();
    }

    @Override
    public void onGetDataNext(FaceBookLoginResponse response) {
        dismissLoadingView();
        if (response.getStatus() == Constant.HTTP_OK) {
            Acache.get(this).put(AcacheKeys.TOKEN, response.getData().getToken());
            EventMsg msg = new EventMsg();
            msg.setMsg(Events.LOGIN_SUCCESS);
            RxBus.getInstance().post(msg);
            finish();
        } else {
            tvLoginByFacebook.setText(getStringResource(R.string.login_click_retry_hint));
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(LoginResponse response) {}

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }
}
